package com.qzyh.esb.egsa.utils;

import com.qzyh.esb.egsa.bean.bo.ParentTreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class TreeBuilder {

    public static<T extends ParentTreeNode<T>> List<T> buildTree(List<T> zoneList) {
        Map<String, List<T>> zoneByParentIdMap = zoneList.stream().collect(Collectors.groupingBy(T::getParentId));
        zoneList.forEach(zone -> zone.setChildren(zoneByParentIdMap.get(zone.getId())));
        return zoneList.stream().filter(v -> v.getParentId().equals("0")).collect(Collectors.toList());
    }

    public static<T extends ParentTreeNode<T>> List<String> getFatherTree(List<T> list, String id){
        List<String> result = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (id.equals(list.get(i).getId())){
                result.add(list.get(i).getId());
                return  result;
            } else if (list.get(i).getChildren() !=null && list.get(i).getChildren().size() > 0){
                List<String> result1 = getFatherTree(list.get(i).getChildren(), id);
                if (result1 != null && result1.size() > 0){
                    result = result1;
                    result.add(list.get(i).getId());
                    return result;
                }
            }
        }
        return result;
    }


}